package com.upb.webserver.dao.mapper;

import cn.hutool.core.collection.CollectionUtil;
import com.upb.webserver.common.constant.Constant;
import com.upb.webserver.common.pojo.order.ApplicationUnionOrderParam;
import com.upb.webserver.common.pojo.order.ChainUnionOrderParam;
import com.upb.webserver.common.tools.JsonUtils;
import com.upb.webserver.dao.entity.TbWorkOrder;
import com.upb.webserver.dao.entity.TbWorkOrderExample;
import com.upb.webserver.dao.entity.TbWorkOrderExample.Criteria;
import com.upb.webserver.dao.entity.TbWorkOrderExample.Criterion;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class TbWorkOrderSqlProvider {

    /**
     * @param param
     * @return
     */
    public String unionQueryFromChainAndWorkOrder(ChainUnionOrderParam param) {
        SQL sql_1 = new SQL();
        sql_1.SELECT("id as chainId");
        sql_1.SELECT("null as workOrderId");
        sql_1.SELECT("gmt_modified");
        sql_1.FROM("tb_chain");
        SQL sql_2 = new SQL();
        sql_2.SELECT("null as chainId");
        sql_2.SELECT("id as workOrderId");
        sql_2.SELECT("gmt_modified");
        sql_2.FROM("tb_work_order");
        //append query param
        appendQueryParamOfChainUniqueOrder(sql_1, sql_2, param);
        StringBuilder sqlBuilder = new StringBuilder(sql_1.toString());
        sqlBuilder.append(" union ");
        sqlBuilder.append(sql_2.toString());
        sqlBuilder.append(String.format(" order by gmt_modified %1s", param.getSortTypeEnum().getValue()));
        //param limit
        sqlBuilder.append(" limit ");
        sqlBuilder.append(Optional.ofNullable(param.getPageNumber()).map(page -> (page - 1) * param.getPageSize()).orElse(0));
        sqlBuilder.append(",");
        sqlBuilder.append(param.getPageSize());
        return sqlBuilder.toString();
    }

    /***
     *
     * @param param
     * @return
     */
    public String unionQueryCountFromChainAndWorkOrder(ChainUnionOrderParam param) {
        SQL sql_1 = new SQL();
        sql_1.SELECT("count(1) a");
        sql_1.FROM("tb_chain");
        SQL sql_2 = new SQL();
        sql_2.SELECT("count(1) a");
        sql_2.FROM("tb_work_order");
        //append query param
        appendQueryParamOfChainUniqueOrder(sql_1, sql_2, param);
        StringBuilder sqlBuilder1 = new StringBuilder(sql_1.toString());
        sqlBuilder1.append(" union all ");
        sqlBuilder1.append(sql_2.toString());
        StringBuilder sqlBuilder2 = new StringBuilder();
        sqlBuilder2.append("select sum(b.a) from(");
        sqlBuilder2.append(sqlBuilder1);
        sqlBuilder2.append(") as b");
        return sqlBuilder2.toString();
    }

    /**
     * @param sql_1
     * @param sql_2
     * @param param
     */
    private void appendQueryParamOfChainUniqueOrder(SQL sql_1, SQL sql_2, ChainUnionOrderParam param) {
        sql_1.WHERE(buildCollectionParamOfQueryColumn("id", param.getChainIdSet()));
        //        sql_2.WHERE(" target_table is null");
        //tb_chain只查成功的数据，相反，tb_work_order除了成功，其他的数据都包含
        sql_1.WHERE(String.format(" create_status in(%s)", Constant.CHAIN_OR_APP_STATUS_DEPLOY_SUCCESS.stream().map(s -> String.valueOf(s)).collect(Collectors.joining(","))));
        sql_2.WHERE(String.format(" status not in(%s)", Constant.WORK_ORDER_STATUS_DEPLOY_SUCCESS.stream().map(s -> String.valueOf(s)).collect(Collectors.joining(","))));
        sql_2.WHERE(buildCollectionParamOfQueryColumn("type", Constant.ORDER_TYPE_LIST_NEW_CHAIN));
        sql_2.WHERE(buildCollectionParamOfQueryColumn("id", param.getWorkOrderIdSet()));
        if (CollectionUtil.isNotEmpty(param.getChainStatusSet()) && CollectionUtil.isNotEmpty(param.getWorkOrderStatusSet())) {
            sql_1.WHERE(buildCollectionParamOfQueryColumn("create_status", param.getChainStatusSet()));
            sql_2.WHERE(buildCollectionParamOfQueryColumn("status", param.getWorkOrderStatusSet()));
        } else if (CollectionUtil.isNotEmpty(param.getChainStatusSet())) {
            sql_1.WHERE(buildCollectionParamOfQueryColumn("create_status", param.getChainStatusSet()));
            sql_2.WHERE("0>1");
        } else if (CollectionUtil.isNotEmpty(param.getWorkOrderStatusSet())) {
            sql_1.WHERE("0>1");
            sql_2.WHERE(buildCollectionParamOfQueryColumn("status", param.getWorkOrderStatusSet()));
        }
    }

    /**
     * @param columnName   字段名
     * @param columnValues 字段可能只
     * @return
     */
    private String buildCollectionParamOfQueryColumn(String columnName, Collection<?> columnValues) {
        if (CollectionUtil.isEmpty(columnValues)) {
            return "1=1";
        }
        if (columnValues.size() == 1 && columnValues.contains(Integer.MIN_VALUE)) {
            return "0>1";
        }
        StringBuilder sqlB = new StringBuilder(String.format(" %s in (", columnName));
        columnValues.stream().forEach(value -> sqlB.append(value).append(","));
        sqlB.append(")");
        sqlB.deleteCharAt(sqlB.lastIndexOf(","));
        return sqlB.toString();
    }

    /**
     * @param param
     * @return
     */
    public String unionQueryFromApplicationAndWorkOrder(ApplicationUnionOrderParam param) {
        SQL sql_1 = new SQL();
        sql_1.SELECT("id as applicationId");
        sql_1.SELECT("null as workOrderId");
        sql_1.SELECT("gmt_modified");
        sql_1.FROM("tb_application");
        SQL sql_2 = new SQL();
        sql_2.SELECT("null as applicationId");
        sql_2.SELECT("id as workOrderId");
        sql_2.SELECT("gmt_modified");
        sql_2.FROM("tb_work_order");
        //append query param
        appendQueryParamOfApplicationUniqueOrder(sql_1, sql_2, param);
        StringBuilder sqlBuilder = new StringBuilder(sql_1.toString());
        sqlBuilder.append(" union ");
        sqlBuilder.append(sql_2.toString());
        sqlBuilder.append(String.format(" order by gmt_modified %1s", param.getSortTypeEnum().getValue()));
        //param limit
        sqlBuilder.append(" limit ");
        sqlBuilder.append(Optional.ofNullable(param.getPageNumber()).map(page -> (page - 1) * param.getPageSize()).orElse(0));
        sqlBuilder.append(",");
        sqlBuilder.append(param.getPageSize());
        return sqlBuilder.toString();
    }

    /***
     *
     * @param param
     * @return
     */
    public String unionQueryCountFromApplicationAndWorkOrder(ApplicationUnionOrderParam param) {
        SQL sql_1 = new SQL();
        sql_1.SELECT("count(1) a");
        sql_1.FROM("tb_application");
        SQL sql_2 = new SQL();
        sql_2.SELECT("count(1) a");
        sql_2.FROM("tb_work_order");
        //append query param
        appendQueryParamOfApplicationUniqueOrder(sql_1, sql_2, param);
        StringBuilder sqlBuilder1 = new StringBuilder(sql_1.toString());
        sqlBuilder1.append(" union all ");
        sqlBuilder1.append(sql_2.toString());
        StringBuilder sqlBuilder2 = new StringBuilder();
        sqlBuilder2.append("select sum(b.a) from(");
        sqlBuilder2.append(sqlBuilder1);
        sqlBuilder2.append(") as b");
        return sqlBuilder2.toString();
    }

    /**
     * @param sql_1
     * @param sql_2
     * @param param
     */
    private void appendQueryParamOfApplicationUniqueOrder(SQL sql_1, SQL sql_2, ApplicationUnionOrderParam param) {
        if (param.getChainId() != null) {
            sql_1.WHERE(String.format(" chain_id =%1d", param.getChainId()));
        }
        sql_1.WHERE(buildCollectionParamOfQueryColumn("id", param.getApplicationIdSet()));
        //tb_application只查成功的数据，相反，tb_work_order除了成功，其他的数据都包含
        sql_1.WHERE(String.format(" create_status in(%s)", Constant.CHAIN_OR_APP_STATUS_DEPLOY_SUCCESS.stream().map(s -> String.valueOf(s)).collect(Collectors.joining(","))));
        sql_2.WHERE(String.format(" status not in(%s)", Constant.WORK_ORDER_STATUS_DEPLOY_SUCCESS.stream().map(s -> String.valueOf(s)).collect(Collectors.joining(","))));
        sql_2.WHERE(buildCollectionParamOfQueryColumn("type", Constant.ORDER_TYPE_LIST_NEW_APP));
        sql_2.WHERE(buildCollectionParamOfQueryColumn("id", param.getWorkOrderIdSet()));
        if (CollectionUtil.isNotEmpty(param.getApplicationStatusSet()) && CollectionUtil.isNotEmpty(param.getWorkOrderStatusSet())) {
            sql_1.WHERE(buildCollectionParamOfQueryColumn("create_status", param.getApplicationStatusSet()));
            sql_2.WHERE(buildCollectionParamOfQueryColumn("status", param.getWorkOrderStatusSet()));
        } else if (CollectionUtil.isNotEmpty(param.getApplicationStatusSet())) {
            sql_1.WHERE(buildCollectionParamOfQueryColumn("create_status", param.getApplicationStatusSet()));
            sql_2.WHERE("0>1");
        } else if (CollectionUtil.isNotEmpty(param.getWorkOrderStatusSet())) {
            sql_1.WHERE("0>1");
            sql_2.WHERE(buildCollectionParamOfQueryColumn("status", param.getWorkOrderStatusSet()));
        }
    }

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public static final String ALL_COLUMN_FIELDS = "id,type,status,target_table,target_id,create_from_platform,create_by,modify_by,close_by_manager,gmt_create,gmt_modified,detail,description";

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String countByExample(TbWorkOrderExample example) {
        SQL sql = new SQL();
        sql.SELECT("count(*)").FROM("tb_work_order");
        applyWhere(sql, example, false);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String deleteByExample(TbWorkOrderExample example) {
        SQL sql = new SQL();
        sql.DELETE_FROM("tb_work_order");
        applyWhere(sql, example, false);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String insertSelective(TbWorkOrder record) {
        SQL sql = new SQL();
        sql.INSERT_INTO("tb_work_order");
        if (record.getType() != null) {
            sql.VALUES("type", "#{type,jdbcType=TINYINT}");
        }
        if (record.getStatus() != null) {
            sql.VALUES("status", "#{status,jdbcType=TINYINT}");
        }
        if (record.getTargetTable() != null) {
            sql.VALUES("target_table", "#{targetTable,jdbcType=VARCHAR}");
        }
        if (record.getTargetId() != null) {
            sql.VALUES("target_id", "#{targetId,jdbcType=INTEGER}");
        }
        if (record.getCreateFromPlatform() != null) {
            sql.VALUES("create_from_platform", "#{createFromPlatform,jdbcType=TINYINT}");
        }
        if (record.getCreateBy() != null) {
            sql.VALUES("create_by", "#{createBy,jdbcType=INTEGER}");
        }
        if (record.getModifyBy() != null) {
            sql.VALUES("modify_by", "#{modifyBy,jdbcType=INTEGER}");
        }
        if (record.getCloseByManager() != null) {
            sql.VALUES("close_by_manager", "#{closeByManager,jdbcType=INTEGER}");
        }
        if (record.getGmtCreate() != null) {
            sql.VALUES("gmt_create", "#{gmtCreate,jdbcType=TIMESTAMP}");
        }
        if (record.getGmtModified() != null) {
            sql.VALUES("gmt_modified", "#{gmtModified,jdbcType=TIMESTAMP}");
        }
        if (record.getDetail() != null) {
            sql.VALUES("detail", "#{detail,jdbcType=LONGVARCHAR}");
        }
        if (record.getDescription() != null) {
            sql.VALUES("description", "#{description,jdbcType=LONGVARCHAR}");
        }
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String selectByExampleWithBLOBs(TbWorkOrderExample example) {
        SQL sql = new SQL();
        if (example != null && example.isDistinct()) {
            sql.SELECT_DISTINCT("id");
        } else {
            sql.SELECT("id");
        }
        sql.SELECT("type");
        sql.SELECT("status");
        sql.SELECT("target_table");
        sql.SELECT("target_id");
        sql.SELECT("create_from_platform");
        sql.SELECT("create_by");
        sql.SELECT("modify_by");
        sql.SELECT("close_by_manager");
        sql.SELECT("gmt_create");
        sql.SELECT("gmt_modified");
        sql.SELECT("detail");
        sql.SELECT("description");
        sql.FROM("tb_work_order");
        applyWhere(sql, example, false);
        log.debug("fix order by --> {}", example.getOrderByClause());
        if (example != null && example.getOrderByClause() != null) {
            sql.ORDER_BY(example.getOrderByClause());
        }
        log.debug("fix order by full --> {}", sql.toString());
        // add pagination for mysql with limit clause 
        StringBuilder sqlBuilder = new StringBuilder(sql.toString());
        if (example != null && (example.getStart() > -1 || example.getCount() > -1)) {
            sqlBuilder.append(" limit ");
            if (example.getStart() > -1 && example.getCount() > -1) {
                sqlBuilder.append(example.getStart()).append(",").append(example.getCount());
            } else if (example.getStart() > -1) {
                sqlBuilder.append(example.getStart());
            } else if (example.getCount() > -1) {
                sqlBuilder.append(example.getCount());
            }
        }
        return sqlBuilder.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String selectByExample(TbWorkOrderExample example) {
        SQL sql = new SQL();
        if (example != null && example.isDistinct()) {
            sql.SELECT_DISTINCT("id");
        } else {
            sql.SELECT("id");
        }
        sql.SELECT("type");
        sql.SELECT("status");
        sql.SELECT("target_table");
        sql.SELECT("target_id");
        sql.SELECT("create_from_platform");
        sql.SELECT("create_by");
        sql.SELECT("modify_by");
        sql.SELECT("close_by_manager");
        sql.SELECT("gmt_create");
        sql.SELECT("gmt_modified");
        sql.FROM("tb_work_order");
        applyWhere(sql, example, false);
        if (example != null && example.getOrderByClause() != null) {
            sql.ORDER_BY(example.getOrderByClause());
        }
        // add pagination for mysql with limit clause 
        StringBuilder sqlBuilder = new StringBuilder(sql.toString());
        if (example != null && (example.getStart() > -1 || example.getCount() > -1)) {
            sqlBuilder.append(" limit ");
            if (example.getStart() > -1 && example.getCount() > -1) {
                sqlBuilder.append(example.getStart()).append(",").append(example.getCount());
            } else if (example.getStart() > -1) {
                sqlBuilder.append(example.getStart());
            } else if (example.getCount() > -1) {
                sqlBuilder.append(example.getCount());
            }
        }
        return sqlBuilder.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String updateByExampleSelective(Map<String, Object> parameter) {
        TbWorkOrder record = (TbWorkOrder) parameter.get("record");
        TbWorkOrderExample example = (TbWorkOrderExample) parameter.get("example");
        SQL sql = new SQL();
        sql.UPDATE("tb_work_order");
        if (record.getId() != null) {
            sql.SET("id = #{record.id,jdbcType=INTEGER}");
        }
        if (record.getType() != null) {
            sql.SET("type = #{record.type,jdbcType=TINYINT}");
        }
        if (record.getStatus() != null) {
            sql.SET("status = #{record.status,jdbcType=TINYINT}");
        }
        if (record.getTargetTable() != null) {
            sql.SET("target_table = #{record.targetTable,jdbcType=VARCHAR}");
        }
        if (record.getTargetId() != null) {
            sql.SET("target_id = #{record.targetId,jdbcType=INTEGER}");
        }
        if (record.getCreateFromPlatform() != null) {
            sql.SET("create_from_platform = #{record.createFromPlatform,jdbcType=TINYINT}");
        }
        if (record.getCreateBy() != null) {
            sql.SET("create_by = #{record.createBy,jdbcType=INTEGER}");
        }
        if (record.getModifyBy() != null) {
            sql.SET("modify_by = #{record.modifyBy,jdbcType=INTEGER}");
        }
        if (record.getCloseByManager() != null) {
            sql.SET("close_by_manager = #{record.closeByManager,jdbcType=INTEGER}");
        }
        if (record.getGmtCreate() != null) {
            sql.SET("gmt_create = #{record.gmtCreate,jdbcType=TIMESTAMP}");
        }
        if (record.getGmtModified() != null) {
            sql.SET("gmt_modified = #{record.gmtModified,jdbcType=TIMESTAMP}");
        }
        if (record.getDetail() != null) {
            sql.SET("detail = #{record.detail,jdbcType=LONGVARCHAR}");
        }
        if (record.getDescription() != null) {
            sql.SET("description = #{record.description,jdbcType=LONGVARCHAR}");
        }
        applyWhere(sql, example, true);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String updateByExampleWithBLOBs(Map<String, Object> parameter) {
        SQL sql = new SQL();
        sql.UPDATE("tb_work_order");
        sql.SET("id = #{record.id,jdbcType=INTEGER}");
        sql.SET("type = #{record.type,jdbcType=TINYINT}");
        sql.SET("status = #{record.status,jdbcType=TINYINT}");
        sql.SET("target_table = #{record.targetTable,jdbcType=VARCHAR}");
        sql.SET("target_id = #{record.targetId,jdbcType=INTEGER}");
        sql.SET("create_from_platform = #{record.createFromPlatform,jdbcType=TINYINT}");
        sql.SET("create_by = #{record.createBy,jdbcType=INTEGER}");
        sql.SET("modify_by = #{record.modifyBy,jdbcType=INTEGER}");
        sql.SET("close_by_manager = #{record.closeByManager,jdbcType=INTEGER}");
        sql.SET("gmt_create = #{record.gmtCreate,jdbcType=TIMESTAMP}");
        sql.SET("gmt_modified = #{record.gmtModified,jdbcType=TIMESTAMP}");
        sql.SET("detail = #{record.detail,jdbcType=LONGVARCHAR}");
        sql.SET("description = #{record.description,jdbcType=LONGVARCHAR}");
        TbWorkOrderExample example = (TbWorkOrderExample) parameter.get("example");
        applyWhere(sql, example, true);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String updateByExample(Map<String, Object> parameter) {
        SQL sql = new SQL();
        sql.UPDATE("tb_work_order");
        sql.SET("id = #{record.id,jdbcType=INTEGER}");
        sql.SET("type = #{record.type,jdbcType=TINYINT}");
        sql.SET("status = #{record.status,jdbcType=TINYINT}");
        sql.SET("target_table = #{record.targetTable,jdbcType=VARCHAR}");
        sql.SET("target_id = #{record.targetId,jdbcType=INTEGER}");
        sql.SET("create_from_platform = #{record.createFromPlatform,jdbcType=TINYINT}");
        sql.SET("create_by = #{record.createBy,jdbcType=INTEGER}");
        sql.SET("modify_by = #{record.modifyBy,jdbcType=INTEGER}");
        sql.SET("close_by_manager = #{record.closeByManager,jdbcType=INTEGER}");
        sql.SET("gmt_create = #{record.gmtCreate,jdbcType=TIMESTAMP}");
        sql.SET("gmt_modified = #{record.gmtModified,jdbcType=TIMESTAMP}");
        TbWorkOrderExample example = (TbWorkOrderExample) parameter.get("example");
        applyWhere(sql, example, true);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String updateByPrimaryKeySelective(TbWorkOrder record) {
        SQL sql = new SQL();
        sql.UPDATE("tb_work_order");
        if (record.getType() != null) {
            sql.SET("type = #{type,jdbcType=TINYINT}");
        }
        if (record.getStatus() != null) {
            sql.SET("status = #{status,jdbcType=TINYINT}");
        }
        if (record.getTargetTable() != null) {
            sql.SET("target_table = #{targetTable,jdbcType=VARCHAR}");
        }
        if (record.getTargetId() != null) {
            sql.SET("target_id = #{targetId,jdbcType=INTEGER}");
        }
        if (record.getCreateFromPlatform() != null) {
            sql.SET("create_from_platform = #{createFromPlatform,jdbcType=TINYINT}");
        }
        if (record.getCreateBy() != null) {
            sql.SET("create_by = #{createBy,jdbcType=INTEGER}");
        }
        if (record.getModifyBy() != null) {
            sql.SET("modify_by = #{modifyBy,jdbcType=INTEGER}");
        }
        if (record.getCloseByManager() != null) {
            sql.SET("close_by_manager = #{closeByManager,jdbcType=INTEGER}");
        }
        if (record.getGmtCreate() != null) {
            sql.SET("gmt_create = #{gmtCreate,jdbcType=TIMESTAMP}");
        }
        if (record.getGmtModified() != null) {
            sql.SET("gmt_modified = #{gmtModified,jdbcType=TIMESTAMP}");
        }
        if (record.getDetail() != null) {
            sql.SET("detail = #{detail,jdbcType=LONGVARCHAR}");
        }
        if (record.getDescription() != null) {
            sql.SET("description = #{description,jdbcType=LONGVARCHAR}");
        }
        sql.WHERE("id = #{id,jdbcType=INTEGER}");
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    protected void applyWhere(SQL sql, TbWorkOrderExample example, boolean includeExamplePhrase) {
        if (example == null) {
            return;
        }
        String parmPhrase1;
        String parmPhrase1_th;
        String parmPhrase2;
        String parmPhrase2_th;
        String parmPhrase3;
        String parmPhrase3_th;
        if (includeExamplePhrase) {
            parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}";
            parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
            parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}";
            parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
            parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}";
            parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
        } else {
            parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}";
            parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
            parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}";
            parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
            parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}";
            parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
        }
        StringBuilder sb = new StringBuilder();
        List<Criteria> oredCriteria = example.getOredCriteria();
        boolean firstCriteria = true;
        for (int i = 0; i < oredCriteria.size(); i++) {
            Criteria criteria = oredCriteria.get(i);
            if (criteria.isValid()) {
                if (firstCriteria) {
                    firstCriteria = false;
                } else {
                    sb.append(" or ");
                }
                sb.append('(');
                List<Criterion> criterions = criteria.getAllCriteria();
                boolean firstCriterion = true;
                for (int j = 0; j < criterions.size(); j++) {
                    Criterion criterion = criterions.get(j);
                    if (firstCriterion) {
                        firstCriterion = false;
                    } else {
                        sb.append(" and ");
                    }
                    if (criterion.isNoValue()) {
                        sb.append(criterion.getCondition());
                    } else if (criterion.isSingleValue()) {
                        if (criterion.getTypeHandler() == null) {
                            sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j));
                        } else {
                            sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j, criterion.getTypeHandler()));
                        }
                    } else if (criterion.isBetweenValue()) {
                        if (criterion.getTypeHandler() == null) {
                            sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j));
                        } else {
                            sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler()));
                        }
                    } else if (criterion.isListValue()) {
                        sb.append(criterion.getCondition());
                        sb.append(" (");
                        List<?> listItems = (List<?>) criterion.getValue();
                        boolean comma = false;
                        for (int k = 0; k < listItems.size(); k++) {
                            if (comma) {
                                sb.append(", ");
                            } else {
                                comma = true;
                            }
                            if (criterion.getTypeHandler() == null) {
                                sb.append(String.format(parmPhrase3, i, j, k));
                            } else {
                                sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler()));
                            }
                        }
                        sb.append(')');
                    }
                }
                sb.append(')');
            }
        }
        if (sb.length() > 0) {
            sql.WHERE(sb.toString());
        }
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_work_order
     *
     * @mbg.generated
     */
    public String getOneByExample(TbWorkOrderExample example) {
        SQL sql = new SQL();
        if (example != null && example.isDistinct()) {
            sql.SELECT_DISTINCT("id");
        } else {
            sql.SELECT("id");
        }
        sql.SELECT("type");
        sql.SELECT("status");
        sql.SELECT("target_table");
        sql.SELECT("target_id");
        sql.SELECT("create_from_platform");
        sql.SELECT("create_by");
        sql.SELECT("modify_by");
        sql.SELECT("close_by_manager");
        sql.SELECT("gmt_create");
        sql.SELECT("gmt_modified");
        sql.SELECT("detail");
        sql.SELECT("description");
        sql.FROM("tb_work_order");
        applyWhere(sql, example, false);
        if (example != null && example.getOrderByClause() != null) {
            sql.ORDER_BY(example.getOrderByClause());
        }
        StringBuilder sqlBuilder = new StringBuilder(sql.toString());
        sqlBuilder.append(" limit 1 ");
        return sqlBuilder.toString();
    }
}
